#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
namespace ThreadModule
{
    std::uint32_t cnt = 0;
    using threadfunc_t = std::function<void()>;

    enum class TSTATUS
    {
        THREAD_NEW,
        THREAD_RUNNING,
        THREAD_STOP
    };

    class Thread
    {
    private:
        static void *run(void *obj)
        {
            Thread *Self = static_cast<Thread *>(obj);
            pthread_setname_np(pthread_self(), Self->_name.c_str());

            Self->_status = TSTATUS::THREAD_RUNNING;
            if (!Self->_joined)
            {
                pthread_detach(pthread_self());
            }
            Self->_func();
            return nullptr;
        }
        void SetName()
        {
            _name = "thread-" + std::to_string(cnt++);
        }

    public:
        Thread(threadfunc_t func) : _status(TSTATUS::THREAD_NEW), _joined(true), _func(func)
        {
            SetName();
        }
        void EnableDetach()
        {
            if (_status == TSTATUS::THREAD_NEW)
            {
                _joined = false;
            }
        }
        void EnableJoined()
        {
            if (_status == TSTATUS::THREAD_NEW)
            {
                _joined = true;
            }
        }
        bool Start()
        {
            if (_status == TSTATUS::THREAD_RUNNING)
            {
                return true;
            }
            int n = ::pthread_create(&_id, nullptr, run, this);
            if (n != 0)
                return false;
            return true;
        }
        bool Join()
        {
            if(_joined)
            {
                int n=pthread_join(_id,nullptr);
                if(n!=0)
                return false;
                return true;

            }
            return false;

        }
        ~Thread(){}

    private:
        std::string _name;
        pthread_t _id;
        TSTATUS _status;
        bool _joined;
        threadfunc_t _func;
    };

};